package com.woniu.inlet.web.controller;

import com.woniu.exception.UserException;
import com.woniu.inlet.fo.UserFo;
import com.woniu.inlet.vo.Coupon;
import com.woniu.inlet.vo.FixedDayVo;
import com.woniu.inlet.vo.UserCoupon;
import com.woniu.inlet.vo.UserVo;
import com.woniu.outlet.client.UserOpenFeign;
import com.woniu.service.UserDetailService;
import com.woniu.service.bean.AddEarnings;
import com.woniu.service.bean.PayCommand;
import com.woniu.service.domain.UserDetail;
import com.woniu.util.AppUtils;
import com.woniu.util.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@Api("user支付")
public class UserPayController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserDetailService userDetailService;
    @Autowired
    private UserOpenFeign userOpenFeign;

    @GetMapping("/pay/payToken")
    @ApiOperation("获取支付幂等性token")
    public ResponseResult<Object> getPayToken() {
        String payToken = UUID.randomUUID().toString().replace("-", "");
        //测试时候 设置存活时间  --> 上线删除
        stringRedisTemplate.opsForValue().set(payToken, payToken, 60 * 15, TimeUnit.SECONDS);
        return ResponseResult.ok(payToken);
    }


    @PostMapping("/pay/verifyPayPassword")
    @ApiOperation("验证支付密码是否正确")
    public ResponseResult<Object> verifyPayPassword(@RequestBody UserFo userFo) {
        boolean b = userDetailService.verifyPayPassword(userFo);
        if (b)
            return ResponseResult.ok("true");
        else
            return ResponseResult.ok("false");
    }

    @PostMapping("/pay/isPayPassword")
    public boolean isPayPassword(@RequestParam("userId") Integer userId, @RequestParam("payPassword") String payPassword) {
        UserFo userFo = new UserFo();
        userFo.setId(userId);
        userFo.setPayPassword(payPassword);
        return userDetailService.verifyPayPassword(userFo);
    }

    @PostMapping("/pay/payPassword")
    @ApiOperation("修改支付密码")
    public ResponseResult<Object> editPayPassword(@RequestBody UserFo userFo) {
        try {
            userDetailService.updatePayPassword(userFo);
            return ResponseResult.ok("修改支付密码成功！！！");
        } catch (Exception e) {
            return ResponseResult.fail("系统维护中，修改支付密码失败！！！");
        }
    }

    //基金 黄金 定期活期 产品的正常买入
    @PostMapping("/pay/buy")
    @ApiOperation("用户购买产品支付测试")
    public ResponseResult<Object> userPay(@RequestBody UserFo userFo) {
        try {
            PayCommand payCommand = new PayCommand(userFo);
            payCommand.execute();
            return ResponseResult.ok("支付成功！！！");
        } catch (Exception e) {
            if (e instanceof UserException) {
                return ResponseResult.fail(e.getMessage());
            } else {
                e.printStackTrace();
                return ResponseResult.fail("支付系统维护中，请稍后再试！！！");
            }
        }
    }

    @GetMapping("/pay/user/{userId}")
    @ApiOperation("根据用户id获取用户的信息")
    public ResponseResult<Object> getMoneyByUserId(@PathVariable("userId") Integer userId) {
        try {
            UserDetail moneyByUserId = userDetailService.getMoneyByUserId(userId);
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(moneyByUserId, userVo);
            return ResponseResult.ok(userVo);
        } catch (Exception e) {
            if (e instanceof UserException) {
                return ResponseResult.fail(e.getMessage());
            } else {
                e.printStackTrace();
                return ResponseResult.fail("支付系统维护中，请稍后再试！！！");
            }
        }
    }

    //用户充值
    @PostMapping("/pay/user/recharge")
    @ApiOperation("用户充值")
    public ResponseResult<Object> recharge(@RequestBody UserFo userFo) {
        try {
            userDetailService.userRecharge(userFo);
            return ResponseResult.ok("充值成功");
        } catch (Exception e) {
            if (e instanceof UserException) {
                return ResponseResult.fail("充值失败");
            } else {
                e.printStackTrace();
                return ResponseResult.fail("系统维护中，请稍后再试！！！");
            }
        }
    }

    /**
     * 根据金额查询优惠券，金额输入框失去焦点时异步请求
     */
    @PostMapping("/pay/user/getDiscount")
    @ApiOperation("用户获取优惠券")
    public ResponseResult<Object> getDiscount(@RequestBody UserFo userFo) {
        try {
            //需要参数userid、提现金额
            Object object = userOpenFeign.couponPay(userFo.getId(), userFo.getDepositAmount());
            if (object == null || object.equals("")) {
                return ResponseResult.ok("没有可用优惠券");
            }
            return ResponseResult.ok(object);
        } catch (RuntimeException e) {
            return ResponseResult.fail("系统维护中，请稍后再试！！！");
        }
    }

    /**
     * 用户确认提现
     */
    @PostMapping("/pay/user/getDeposit")
    @ApiOperation("用户提现")
    public ResponseResult<Object> getDeposit(@RequestBody UserFo userFo) {
        try {
            //根据userid查询用户
            UserDetail user = userDetailService.getMoneyByUserId(userFo.getId());
            //获取用户的提现金额
            BigDecimal depositAmount = userFo.getDepositAmount();
            UserDetail userDetail = new UserDetail();
            //判断是否使用优惠券
            if (userFo.getCouponId() == null || userFo.getCouponId() == 0) {
                //没有使用优惠券
                //计算手续费
                BigDecimal cost = userFo.getDepositAmount().multiply(new BigDecimal("0.01"));
                userDetail.setRestAmount(user.getRestAmount().subtract(userFo.getDepositAmount().add(cost)));
                userDetail.setUserId(userFo.getId());
                userDetailService.updateUser(userDetail);
                //平台收益添加
                AddEarnings addEarnings = new AddEarnings();
                addEarnings.setDealTime(AppUtils.getNowTimeStr());
                addEarnings.setDealType(AddEarnings.TX);
                addEarnings.setUserId(userFo.getId());
                addEarnings.setDealPrice(userFo.getDepositAmount());
                addEarnings.setDealCharge(cost);
                addEarnings.setProductType("用户提现");
                addEarnings.execute();
            } else if (userFo.getCouponId() != null && userFo.getCouponId() != 0) {
                //使用优惠券
                //计算手续费
                BigDecimal cost = userFo.getDepositAmount().multiply(new BigDecimal("0.01"));
                //根据id查询优惠券
                UserCoupon userCoupon = userOpenFeign.getUsercoupnById(userFo.getCouponId());
                Coupon coupon = userCoupon.getCoupon();
                userDetail.setRestAmount((user.getRestAmount().subtract(userFo.getDepositAmount().add(cost)).add(new BigDecimal(coupon.getPrivilege()))));
                userDetail.setUserId(userFo.getId());
                userDetailService.updateUser(userDetail);
                //openfeign通知用户中心
                userOpenFeign.useCoupon(userFo.getCouponId());
                //平台收益添加
                AddEarnings addEarnings = new AddEarnings();
                addEarnings.setDealTime(AppUtils.getNowTimeStr());
                addEarnings.setDealType(AddEarnings.TX);
                addEarnings.setUserId(userFo.getId());
                addEarnings.setDealPrice(userFo.getDepositAmount());
                addEarnings.setDealCharge(cost);
                addEarnings.setProductType("用户提现");
                addEarnings.execute();
            }
            return ResponseResult.ok("提现成功");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseResult.fail("提现失败请稍后再试");
        }
    }

}
